package net.javalib.gvmax.post.server;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.javalib.gvmax.post.server.util.MiscUtil;
import net.javalib.gvmax.post.server.util.NetUtil;
import net.javalib.gvmax.post.server.util.SMS;
import net.javalib.gvmax.post.server.util.SMSExtractor;
import net.javalib.gvmax.post.server.util.Voicemail;
import net.javalib.gvmax.post.server.util.VoicemailExtractor;

public class MailInServlet extends HttpServlet {
	private static final Logger logger = Logger.getLogger(MailInServlet.class.getName());
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.info("email in");
		Properties props = new Properties(); 
        Session session = Session.getDefaultInstance(props, null);
        DAO dao = new DAO();
        try {
        	MimeMessage email = new MimeMessage(session, req.getInputStream());
        	
        	String account = ((InternetAddress)email.getRecipients(RecipientType.TO)[0]).getAddress().toLowerCase();
    		logger.info("recevied email : "+account);
        	String postUrl = dao.getPostUrl(account);
        	logger.info("post url for "+account+" = "+postUrl);
    		String[] froms = email.getHeader("From");
    		if (froms.length > 0) {
    			String from = froms[0].toLowerCase();
    			if (from.contains("txt.voice.google.com")) {
    				doSMS(account,postUrl,email);
    				return;
    			} 
    			if (from.contains("voice-noreply@google.com")) {
    				doVM(account,postUrl,email);
    				return ;
    			} 
    			if (email.getSubject().contains("missed call")) {
    				// doMissedCall(email);
    				return;
    			} 
    			doConfirmation(email);
    		}

        } catch (Exception e) {
        	e.printStackTrace();
        	logger.log(Level.SEVERE, "UPS Error: "+e.getMessage(), e);
        }
	}

	private void doSMS(String account, String postUrl, MimeMessage email) throws Exception {
		SMS sms = SMSExtractor.getSMS(email);
		logger.info("got SMS for "+account);
		Map<String,String> params = new HashMap<String, String>();
		params.put("type", "SMS");
		params.put("number", sms.number);
		params.put("contact", sms.contact);
		params.put("text", sms.text);
		params.put("receiver", account);
		NetUtil.doPost(postUrl, params);
	}
	
	private void doVM(String account, String postUrl, MimeMessage email) throws Exception {
		Voicemail vm = VoicemailExtractor.extractVoicemailInfo(email);
		logger.info("got VM for "+account);
		Map<String,String> params = new HashMap<String, String>();
		params.put("type", "VM");
		params.put("number", vm.number);
		params.put("contact", vm.contact);
		params.put("text", vm.transcript);
		params.put("link", vm.link);
		params.put("receiver", account);
		NetUtil.doPost(postUrl, params);
	}
	
	private void doConfirmation(MimeMessage email) throws Exception {
		String text = MiscUtil.getEmailText(email);
		if (text.contains("https://mail.google.com")) {
			String link = text.substring(text.indexOf("https://mail.google.com"));
			link = link.substring(0,link.indexOf("\n"));
			try {
				NetUtil.doGet(link);
				return;
			} catch (Exception e) { }
		}
//		// Unhandled
//		String from = email.getHeader("From")[0].toLowerCase();
//       	String to = ((InternetAddress)email.getRecipients(RecipientType.TO)[0]).getAddress().toLowerCase();
//        MailService mailService = MailServiceFactory.getMailService();
//    	Message message = new Message();
//    	message.setTextBody(text);
//    	message.setSubject("Unhandled email : from="+from+", to="+to);
//    	message.setSender(Settings.ADMIN);
//    	// Send to admins
//    	mailService.sendToAdmins(message);
    	    	
	}
	
}
